package com.taikang.auth.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.taikang.auth.entity.Depart;
import com.taikang.auth.entity.User;
import com.taikang.auth.form.DepartForm;
import com.taikang.auth.service.IDepartService;
import com.taikang.auth.service.IUserService;
import com.taikang.base.controller.BaseController;
import com.taikang.base.token.TokenValidate;

/**
 * 部门控制器
 * @creator     taikang
 * @create-time 2016年2月13日   上午9:42:13
 * @email taikang@taikang.com
 * @company www.taikang.com
 * @version 1.0
 */
@Controller("departController")
@Scope("prototype")
@RequestMapping(value = "/admin/auth/depart")
public class DepartController extends BaseController {

	@Resource(name = "departServiceImpl")
	private IDepartService departService;
	@Resource(name = "userServiceImpl")
	private IUserService userService;
	
	
	/**
	 * 显示部门树，默认展开第一级
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/list_depart.htm", method = RequestMethod.POST)
	public ModelAndView listDepartFirstTree(DepartForm model){
		JSONArray root = new JSONArray();
		List<Depart> list=new ArrayList<Depart>();
		// 初次加载
		if(StringUtils.isBlank(model.getPid())){
			// 构造“全部”项
			Depart depart =departService.getDepartById("0");
			JSONObject topJson = makeJsonObject(depart);
			topJson.put("isParent", true);
			topJson.put("open", true);
			list = departService.listDepartByPid("0");
			JSONArray children = new JSONArray();
			for (int i = 0; i < list.size(); i++){
				JSONObject json = makeJsonObject(list.get(i));
				children.add(json);
			}
			topJson.put("children", children);
			root.add(topJson);
			
		// 点击后加载
		}else{
			list = departService.listDepartByPid(model.getPid());
			for (int i = 0; i < list.size(); i++){
				JSONObject json = makeJsonObject(list.get(i));
				root.add(json);
			}
		}
		
		Map<String,String> data = new HashMap<String,String>();
		data.put("data", root.toJSONString());
		
		return ajaxJSON(Status.success, "加载成功",data);
	}
	/**
	 * 用户管理左侧部门组织架构树，根据用户加载部门树
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/list_depart_user.htm", method = RequestMethod.POST)
	public ModelAndView list_depart_user(DepartForm model){
		JSONArray root = new JSONArray();
		List<Depart> list=new ArrayList<Depart>();
		List<Depart> list2=new ArrayList<Depart>();
		String str = "";
		//取出当前用户信息
		User currentUser = userService.getCurrentUser();
		//拼接所有角色代码
		for (int c = 0; c < currentUser.getRoleList().size(); c++) {
			str += currentUser.getRoleList().get(c).getCode()+",";
		}
		//判断角色代码是否为空
		if(StringUtils.isNotBlank(str)){
				//如果角色代码是系统管理员的则查询全部，否则根据条件查询
				if(str.indexOf("00")>=0){
					// 初次加载
					if(StringUtils.isBlank(model.getPid())){
						// 构造“全部”项
						Depart depart =departService.getDepartById("0");
						JSONObject topJson = makeJsonObject(depart);
						topJson.put("isParent", true);
						topJson.put("open", true);
						list = departService.listDepartByPid("0");
						JSONArray children = new JSONArray();
						for (int i = 0; i < list.size(); i++){
							JSONObject json = makeJsonObject(list.get(i));
							children.add(json);
						}
						topJson.put("children", children);
						root.add(topJson);
						
					// 点击后加载
					}else{
						list = departService.listDepartByPid(model.getPid());
						for (int i = 0; i < list.size(); i++){
							JSONObject json = makeJsonObject(list.get(i));
							root.add(json);
						}
					}
				}else{
					// 初次加载
					if(StringUtils.isBlank(model.getPid())){
						// 构造“全部”项
						Depart depart =departService.getDepartById("0");
						JSONObject topJson = makeJsonObject(depart);
						topJson.put("isParent", true);
						topJson.put("open", true);
						/*String departIds = "";
						for (int j = 0; j < currentUser.getDepartList().size(); j++) {
							departIds += currentUser.getDepartList().get(j).getId()+",";
						}*/
						//1.查询当前用户所在部门
						/*List<Depart> depart1 = departService.listDepartByIds(departIds.split(","));*/
						List<Depart> depart1 = currentUser.getDepartList();
						//2.获取所在部门的父级
						List<Depart> allDepart = departService.listDepartByPid("0");
						
						for (int i = 0; i < allDepart.size(); i++) {
							for (int j = 0; j < depart1.size(); j++) {
								if(depart1.get(j).getId().equals(allDepart.get(i).getId()) || depart1.get(j).getParentId().equals(allDepart.get(i).getId())){
									list.add(allDepart.get(i));
								}
							}
						}
						for (int i = 0; i < list.size(); i++) //外循环是循环的次数
						{
						for (int j = list.size() - 1 ; j > i; j--) //内循环是 外循环一次比较的次数
						{
						
						if (list.get(i).getId().equals(list.get(j).getId()))
						{
							list.remove(list.get(j));
						}
						
						}
						}
						/*//3.再按照部门找用户
						List<String> departList = new ArrayList<String>();
						if(depart != null ){
							for (Depart depart2 : depart1) {
								getDepartByParentId(allDepart, depart2.getParentId(),departList);
							}
							for (int i = 0; i < departList.size(); i++) {
								Depart depart3 = departService.getDepartById(departList.get(i));
								list.add(depart3);
							}
						}*/
						JSONArray children = new JSONArray();
						for (int i = 0; i < list.size(); i++){
							if(list.get(i).getLevel()==1){
								JSONObject json = makeJsonObject(list.get(i));
								children.add(json);
							}
						}
						topJson.put("children", children);
						root.add(topJson);
						
					// 点击后加载
					}else{
						list2 = departService.listDepartByPid(model.getPid());
						for (int j = 0; j < currentUser.getDepartList().size(); j++) {
							list.add(departService.getDepartById(currentUser.getDepartList().get(j).getId()));
						}
						for (int i = 0; i < list2.size(); i++) {
							for (int j = 0; j < list.size(); j++){
								if(list2.get(i).getParentId().equals(list.get(j).getId())){
									JSONObject json = makeJsonObject(list2.get(i));
									root.add(json);
									break;
								}else{
									if(list2.get(i).getId().equals(list.get(j).getId())){
										JSONObject json = makeJsonObject(list.get(j));
										root.add(json);
									}else if(list.get(j).getLevel()==3 && list.get(j).getParentId().equals(list2.get(i).getId())){
										Depart depart1 = departService.getDepartById(list.get(j).getParentId());
										if(depart1.getId().equals(list.get(j).getParentId())){
											JSONObject json = makeJsonObject(depart1);
											root.add(json);
										}
									}
								}
							}
						}
						for (int i = 0; i < root.size(); i++) //外循环是循环的次数
						{
						for (int j = root.size() - 1 ; j > i; j--) //内循环是 外循环一次比较的次数
						{
						
						if (root.get(i).equals(root.get(j)))
						{
							root.remove(root.get(j));
						}
						
						}
						}
					}
				}
		}else{
			//如果是admin账号则查询全部，否则根据用户查询
			if(currentUser.getAccount().equals("admin")){
				// 初次加载
				if(StringUtils.isBlank(model.getPid())){
					// 构造“全部”项
					Depart depart =departService.getDepartById("0");
					JSONObject topJson = makeJsonObject(depart);
					topJson.put("isParent", true);
					topJson.put("open", true);
					list = departService.listDepartByPid("0");
					JSONArray children = new JSONArray();
					for (int i = 0; i < list.size(); i++){
						JSONObject json = makeJsonObject(list.get(i));
						children.add(json);
					}
					topJson.put("children", children);
					root.add(topJson);
					
				// 点击后加载
				}else{
					list = departService.listDepartByPid(model.getPid());
					for (int i = 0; i < list.size(); i++){
						JSONObject json = makeJsonObject(list.get(i));
						root.add(json);
					}
				}
			}else{
				// 初次加载
				if(StringUtils.isBlank(model.getPid())){
					// 构造“全部”项
					Depart depart =departService.getDepartById("0");
					JSONObject topJson = makeJsonObject(depart);
					topJson.put("isParent", true);
					topJson.put("open", true);
					for (int j = 0; j < currentUser.getDepartList().size(); j++) {
						if(list.size()<=0){
							list.add(departService.getDepartById(currentUser.getDepartList().get(j).getId()));
						}else{
							for (int i = 0; i < list.size(); i++) {
								if(!currentUser.getDepartList().get(j).getParentId().equals(list.get(i).getId())){
									list.add(departService.getDepartById(currentUser.getDepartList().get(j).getId()));
								}
							}
						}
					}
					JSONArray children = new JSONArray();
					for (int i = 0; i < list.size(); i++){
						JSONObject json = makeJsonObject(list.get(i));
						children.add(json);
					}
					topJson.put("children", children);
					root.add(topJson);
					
				// 点击后加载
				}else{
					list2 = departService.listDepartByPid(model.getPid());
					for (int j = 0; j < currentUser.getDepartList().size(); j++) {
						list.add(departService.getDepartById(currentUser.getDepartList().get(j).getId()));
					}
					for (int i = 0; i < list2.size(); i++) {
						for (int j = 0; j < list.size(); j++){
							if(list2.get(i).getId().equals(list.get(j).getId())){
								JSONObject json = makeJsonObject(list.get(j));
								root.add(json);
							}
						}
					}
				}
			}
		}
		Map<String,String> data = new HashMap<String,String>();
		data.put("data", root.toJSONString());
		
		return ajaxJSON(Status.success, "加载成功",data);
	}
	
	public static void getDepartByParentId(List<Depart> list,String parentId,List<String> result){
		for (Depart depart : list) {
			if(StringUtils.equals(depart.getParentId(), parentId)){
				result.add(depart.getId());
				getDepartByParentId(list, depart.getId(),result);
			}
		}
	}
	
	/**
	 * 跳转到修改部门页面
	 */
	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public ModelAndView edit(DepartForm model) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/auth/depart_add");
		
		Map<String,Object> data = view.getModel();
		data.put("item", model.getItem());
		
		if(StringUtils.isNotBlank(model.getItem().getId())){
			// 获得部门信息
			Depart item = departService.getDepartById(model.getItem().getId());
			data.put("item", item);
		}
		return view;
	}
	
	/**
	 * 新增类别
	 */
	@RequestMapping(value = "/doSaveDepart.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView doSaveDepart(DepartForm model,HttpServletRequest request) throws Exception {
		try {
			User currentUser = userService.getCurrentUser();
			model.getItem().setCreateBy(currentUser.getAccount());
			model.getItem().setUpdateBy(currentUser.getAccount());

			Map<String,String> data = new HashMap<String,String>();
			
			if(StringUtils.isBlank(model.getItem().getId())){
				departService.add(model.getItem());
				data.put("itemId", model.getItem().getId());
			}else{
				departService.update(model.getItem());
			}
			
			return ajaxJSON(Status.success,"保存成功",data);
		} catch (Exception e) {
			String msg = "保存部门节点时发生异常："+e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error,"保存失败",true,request);
		}
	}
	


	/**
	 * 删除
	 * @return 
	 */
	@RequestMapping(value = "/del.htm", method = RequestMethod.POST)
	public ModelAndView del(DepartForm model){
		try {
			List<String> delIds = new ArrayList<String>();
			String[] ids = model.getSelIds().split(",");
			for(String id : ids){
				//判断部门下的人数
				int userCount = userService.getUserCountByDepartId(id);
				if(userCount > 0){
					continue;
				}
				delIds.add(id);
			}
			if(delIds.size()!=0){
				departService.delByIds(delIds.toArray(new String[delIds.size()]));
			}else{
				return ajaxJSON(Status.error,"请先将该部门下的人员转移到其他部门下再删除");
			}
			return ajaxJSON(Status.success,"删除成功");
		} catch (Exception e) {
			String msg = "删除部门时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, msg);
		}
	}
	
	/**
	 * 构造JSON对象
	 * @param depart
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private JSONObject makeJsonObject(Depart depart){
		JSONObject data = new JSONObject();
		data.put("id",depart.getId());
		data.put("name",depart.getName());
		
		//根据部门ID查询部门下的子部门数量
		int childCount = departService.getCountByParentId(depart.getId());
		if(childCount > 0){
			data.put("isParent", true);
		}else{
			data.put("isParent", false);
		}
		
		data.put("parentId",depart.getParentId());
		
		return data;
	}

	/**
	 * 跳转到移动部门页面
	 */
	@RequestMapping(value = "/move.htm", method = RequestMethod.GET)
	public ModelAndView move(DepartForm model) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/auth/depart_move");
		Map<String,Object> data = view.getModel();
		data.put("selIds", model.getSelIds());
		data.put("moveType", model.getMoveType());
		data.put("oldDepartId", model.getOldDepartId());
		return view;
	}
	
	/**
	 * 执行移动部门
	 */
	@RequestMapping(value = "/doMove.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView doMove(DepartForm model,HttpServletRequest request) throws Exception {
		try {
			User currentUser = userService.getCurrentUser();
			departService.doMove(model.getSelIds(), model.getNewDepartId(), currentUser.getAccount());
			return ajaxJSON(Status.success,"移动成功");
		} catch (Exception e) {
			String msg = "移动部门节点时发生异常："+e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, msg);
		}
	}
}